package example.listeners;

import java.io.File;
import java.io.IOException;
import java.util.Collection;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import example.AppConstants;
import example.model.Customer;

/**
 * Listener that reads a json file from disk to its object representation
 * The object representation is kept in the servlet context so to allow
 * any servlet that depends on this file to access the customers data
 */
public class LoadCustomerJsonFile implements ServletContextListener {

    /**
     * Default constructor. 
     */
    public LoadCustomerJsonFile() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent event)  { 
    	ServletContext cnxt = event.getServletContext();
    	try{
    		Collection<Customer> customers = JsonFileLoadUtil.loadCustomers(
    				cnxt.getResourceAsStream(File.separator + AppConstants.CUSTOMERS_FILE));
    		//keep object in servlet context for later use
    		cnxt.setAttribute(AppConstants.CUSTOMERS, customers);

    	} catch (IOException e) {
    		//log error 
    		event.getServletContext().log("Error reading customers json file",e);
    	}
    }

	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent event)  { 
         // TODO Auto-generated method stub
    }
	
}
